<template>
  <div class="merchant-list">
    <el-card class="mb-4">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="分类">
          <el-select filterable v-model="searchForm.categoryId" placeholder="请选择分类" clearable class="w-full">
            <el-option :label="item.categoryName" :value="item.id" v-for="item,index in classList" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="区域">
          <el-select filterable v-model="searchForm.areaId" @change="areaIdChange" placeholder="请选择区域" clearable
            class="w-full">
            <el-option :label="item.areaName" :value="item.areaId" v-for="item,index in areaList" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="楼层">
          <el-select filterable v-model="searchForm.floorId" placeholder="请选择楼层" clearable class="w-full">
            <el-option :label="item.floorName" :value="item.floorId" v-for="item,index in eleseFloor" :key="index" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="品牌店铺">
          <el-select filterable v-model="searchForm.shopId" clearable placeholder="请选择品牌店铺" class="w-full">
            <el-option :label="item.name" :value="item.id" v-for="item,index in merchantList" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="handleAdd" style="margin-left: 30px"
            v-has="'shop:brand:save'">新增店铺</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  
    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" border style="width: 100%;margin-top:15px">
      <!-- <el-table-column prop="floorId" label="所在楼层ID" width="100" /> -->
      <el-table-column prop="floorName" label="楼层名称" />
      <!-- <el-table-column prop="areaId" label="所在区域ID" width="100" /> -->
      <el-table-column prop="areaName" label="区域名称" />
      <!-- <el-table-column prop="categoryId" label="分类ID" width="100" /> -->
      <el-table-column prop="categoryName" label="分类名称" />
      <el-table-column prop="pointsRatio" label="积分比例" />

      <el-table-column prop="address" label="品牌商铺地址" />
      <el-table-column prop="name" label="店铺名称" />
      <el-table-column prop="shopNumber" label="商铺门牌号" />
      <el-table-column prop="logo" label="店铺logo">
        <template #default="{ row }">
          <el-image v-if="row.logo" style="width: 50px; height: 50px" :src="row.logo" :preview-src-list="[row.logo]"
            fit="cover" />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="rating" label="评分" width="80" />
                                          <el-table-column prop="ratingText" label="评分文本" />
                                          <el-table-column prop="reviewCount" label="评价数量" width="100" /> -->
      <el-table-column prop="startTime" label="开始营业时间" />
      <el-table-column prop="endTime" label="结束营业时间" />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '正常' : '关闭' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button type="text" v-has="'shop:brand:update'" @click="openEmployeeList(row)">查看员工</el-button>
          <el-button type="text" v-has="'shop:brand:update'" @click="openCouponList(row)">查看优惠券</el-button>
          <el-button type="text" v-has="'shop:brand:update'" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" style="color: #f56c6c" v-has="'shop:brand:delete'"
            @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  
    <el-dialog :close-on-click-modal="false" title="员工列表" :visible.sync="registrationDialogVisible"
      @close="registrationDialogVisible =false" width="80%">
      <el-table :data="registrationList" border style="width: 100%; margin-top: 15px" class="dialog_height">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="userNo" label="会员编号" />
        <el-table-column prop="nickname" label="昵称" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="credit" label="积分" />
        <el-table-column prop="type" label="用户类型" width="100">
          <template #default="{ row }">
            <el-tag>{{ row.type === 1 ? '用户' : row.type === 2 ? '员工' : '商管' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="是否为商管" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.type === 3" type="success">是</el-tag>
            <el-tag v-else type="info">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="position" label="职位" />
      </el-table>
    </el-dialog>
  
    <el-dialog :close-on-click-modal="false" title="优惠券列表" :visible.sync="couponDialogVisible"
      @close="couponDialogVisible =false" width="80%">
      <el-table :data="couponList" border style="width: 100%; margin-top: 15px" class="dialog_height">
        <el-table-column prop="title" label="优惠券名称" />
        <el-table-column prop="couponValue" label="优惠券面值">
          <template #default="{ row }">
            {{ row.couponValue }}元
          </template>
        </el-table-column>
        <el-table-column prop="useThreshold" label="使用门槛">
          <template #default="{ row }">
            {{ row.useThreshold }}元
          </template>
        </el-table-column>
        <el-table-column prop="price" label="售价">
          <template #default="{ row }">
            {{ row.price }}元
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" />
        <el-table-column prop="effectStart" label="有效期" width="200">
          <template #default="{ row }">
            {{ row.effectStart }} 至 {{ row.effectEnd }}
          </template>
        </el-table-column>
        <el-table-column prop="shelf" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.shelf === 1 ? 'success' : 'danger'">
              {{ row.shelf === 1 ? '正常' : '关闭' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next" :total="total">
      </el-pagination>
    </div>
  
    <!-- 新增/编辑弹窗 -->
    <el-dialog :close-on-click-modal="false" :title="dialogType === 'add' ? '新增' : '编辑'" :visible.sync="dialogVisible"
      width="80%" top="5vh" @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="所在楼层" prop="floorId">
          <el-select filterable v-model="form.floorId" placeholder="请选择所在楼层" clearable style="width: 100%">
            <el-option v-for="item in floorList" :key="item.floorId" :label="item.floorName + '-' +  item.areaName"
              :value="item.floorId" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="所在区域" prop="areaId">
                                                  <el-select filterable  v-model="form.areaId" placeholder="请选择所在区域" filterable clearable style="width: 100%">
                                                      <el-option v-for="item in areaList" :key="item.areaId" :label="item.areaName" :value="item.areaId" />
                                                  </el-select>
                                              </el-form-item> -->
        <el-form-item label="分类" prop="categoryId">
          <el-select filterable v-model="form.categoryId" placeholder="请选择分类" clearable style="width: 100%">
            <el-option v-for="item in classList" :key="item.id" :label="item.categoryName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="店铺名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入店铺名称" />
        </el-form-item>
        <el-form-item label="商铺门牌号" prop="shopNumber">
          <el-input v-model="form.shopNumber" placeholder="请输入商铺门牌号" />
        </el-form-item>
        <el-form-item label="品牌商铺地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入品牌商铺地址" />
        </el-form-item>
        <el-form-item label="积分比例" prop="pointsRatio">
                    <el-input v-model="form.pointsRatio" placeholder="请输入积分比例"> 
                      <!-- <template slot="append">%</template> -->
                    </el-input>
               </el-form-item>
        <el-form-item label="店铺logo" prop="logo">
          <el-upload class="image-uploader" :headers="headers" :action="$uploadUrl" :show-file-list="false"
            :on-success="handleIconSuccess" :before-upload="beforeImageUpload">
            <img v-if="form.logo" :src="form.logo" class="uploaded-image" />
            <div v-else class="upload-placeholder">
              <i class="el-icon-plus"></i>
              <div class="upload-text">点击上传图片</div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="店铺轮播图" prop="imageUrl">
          <el-upload class="image-uploader" :headers="headers" :action="$uploadUrl" :show-file-list="false"
            :on-success="handleIconSuccess1" :before-upload="beforeImageUpload">
            <div class="flex_flex">
              <div v-for="item,index in form.imageUrl" :key="index" class="image-item">
                <img :src="item" class="uploaded-image" />
                <div class="delete-image" @click="handleDeleteImage(index)">删除</div>
              </div>
              <div class="upload-placeholder">
                <i class="el-icon-plus"></i>
                <div class="upload-text">点击上传图片</div>
              </div>
            </div>
          </el-upload>
        </el-form-item>
        <!-- <el-form-item label="评分" prop="rating">
                                                  <div class="flex_contents">
                                                  <el-rate v-model="form.rating" :max="5" :texts="['1分', '2分', '3分', '4分', '5分']" show-text />
                                                  </div>
                                              </el-form-item>
                                              <el-form-item label="评分文本" prop="ratingText">
                                                  <el-input v-model="form.ratingText" placeholder="请输入评分文本" />
                                              </el-form-item>
                                              <el-form-item label="评价数量" prop="reviewCount">
                                                  <el-input-number v-model="form.reviewCount" :min="0" placeholder="请输入评价数量" />
                                              </el-form-item> -->
        <el-form-item label="营业时间">
          <el-col :span="11">
            <el-form-item prop="startTime">
              <el-time-select :picker-options="{
      start: '00:00',
        step: '00:15',
        end: '23:59'
    }" v-model="form.startTime"  value-format="HH:mm" placeholder="开始时间" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="2" class="text-center">至</el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
               <el-time-select :picker-options="{
      start: '00:00',
        step: '00:15',
        end: '23:59'
    }"  v-model="form.endTime" value-format="HH:mm" placeholder="结束时间" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="店铺介绍" prop="description">
          <!-- <el-input v-model="form.description" placeholder="请输入店铺介绍" /> -->
          <EditorBar style="width: 100%" v-model="form.description" :catchData="catchDataAgreement"></EditorBar>
  
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import EditorBar from "@/components/WangEnduit.vue";

export default {
  name: 'MerchantList',
  components: {
    EditorBar
  },
  data() {
    return {
      headers: {
        'token': localStorage.getItem('token')
      },
      registrationDialogVisible: false,
      registrationList: [],
      classList: [],
      areaList: [],
      floorList: [],
      eleseFloor: [],
      // 搜索表单
      searchForm: {
        categoryId: '',
        areaId: '',
        floorId: '',
        shopId: ''
      },
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 表格数据
      tableData: [],
      loading: false,
      // 弹窗相关
      dialogVisible: false,
      dialogType: 'add', // add 或 edit
      uploadUrl: '', // 上传地址
      form: {
        floorId: '',
        // areaId: '',
        categoryId: '',
        name: '',
        shopNumber: '',
        address: '',
        logo: '',
        imageUrl: [],
        // rating: 0,
        // ratingText: '',
        // reviewCount: 0,
        startTime: '09:30',
        pointsRatio:'',
        endTime: '21:30',
        status: 1,
        description: ''
      },
      // 表单校验规则
      rules: {
        floorId: [{ required: true, message: '请选择所在楼层', trigger: 'change' }],
        // areaId: [{ required: true, message: '请选择所在区域', trigger: 'change' }],
        categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
        name: [{ required: true, message: '请输入店铺名称', trigger: 'blur' }],
        shopNumber: [{ required: true, message: '请输入商铺门牌号', trigger: 'blur' }],
        // pointsRatio: [{ required: true, message: '请输入积分比例', trigger: 'blur' }],
        logo: [{ required: true, message: '请上传店铺logo', trigger: 'change' }],
        // rating: [{ required: true, message: '请选择评分', trigger: 'change' }],
        // ratingText: [{ required: true, message: '请输入评分文本', trigger: 'blur' }],
        // reviewCount: [{ required: true, message: '请输入评价数量', trigger: 'change' }],
        // startTime: [{ required: true, message: '请选择开始营业时间', trigger: 'change' }],
        // endTime: [{ required: true, message: '请选择结束营业时间', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        description: [{ required: true, message: '请输入店铺介绍', trigger: 'blur' }],
        imageUrl: [{ required: true, message: '请上传店铺轮播图', trigger: 'change' }],
      },
      areaName: '',
      description: '',
      sortOrder: '',
      merchantList: [],
      couponList: [],
      couponDialogVisible: false,
    }
  },
  created() {
    this.getList();
    this.getMerchantList()
    this.queryFloorList();
    this.mallAreaList()
    this.queryFloorClass()
  },
  methods: {
    areaIdChange(e) {
      this.searchForm.floorId = ''
      if (e) {
        this.eleseFloor = this.floorList.filter(item => item.areaId === e)
      } else {
        this.eleseFloor = this.floorList
      }
    },
    async openCouponList(row) {
      this.couponDialogVisible = true
      const { data } = await this.$api.couponList({
        page: 1,
        size: 1000,
        condition: {
          categoryId: '',
          shelf: '',
          shopId: row.id
        }
      })
      console.log(data, 'data');
      this.couponList = data.result.records
    },
    async openEmployeeList(row) {
      this.registrationDialogVisible = true
      const { data } = await this.$api.getUserLists({
        page: 1,
        size: 1000,
        condition: {
          nickname: '',
          phone: '',
          shelf: '',
          type: 2,
          shopId: row.id,
        }
      })
      console.log(data, 'data');
      this.registrationList = data.result.records
    },
    //基本信息富文本编辑
    catchDataAgreement(val) {
      this.form.description = val;
    },
    handleDeleteImage(index) {
      this.form.imageUrl.splice(index, 1)
    },
    async queryFloorClass() {
      this.loading = true
      try {
        const { data } = await this.$api.floorCategoryList()
        this.classList = data.result
        // this.total = data.result.total
      } catch (error) {
        console.error('获取商家列表失败：', error)
      } finally {
        this.loading = false
      }
    },
    async queryFloorList() {
      this.loading = true
      try {
        const { data } = await this.$api.getFloorList({
          page: 1,
          size: 10000,
          condition: {
            floorName: '',
          }
        })
        this.floorList = data.result.records
        this.eleseFloor = data.result.records
        console.log(this.floorList, '楼层列表');
      } catch (error) {
      } finally {
      }
    },
    async mallAreaList() {
      this.loading = true
      try {
        const { data } = await this.$api.getMallAreaList({
          page: 1,
          size: 10000,
          condition: {
            areaName: '',
          }
        })
        this.areaList = data.result.records
      } catch (error) {
      } finally {
      }
    },
    async getMerchantList() {
      const { data } = await this.$api.shopPageList({
        page: 1,
        size: 10000,
        condition: {
          categoryId: '',
          areaId: '',
          floorId: '',
        }
      })
      console.log(data, '111111');
      this.merchantList = data.result.records
    },
    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        const { data } = await this.$api.shopPageList({
          page: this.currentPage,
          size: this.pageSize,
          condition: {
            ...this.searchForm
          }
        })
        this.tableData = data.result.records
        this.total = data.result.total
      } catch (error) {
        console.error('获取商家列表失败：', error)
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.getList()
    },

    // 图片上传成功回调
    async handleIconSuccess(res) {
      console.log(res, 'resresres')
      this.form.logo = res.result.filePath
    },
    // 图片上传成功回调
    async handleIconSuccess1(res) {
      this.form.imageUrl.push(res.result.filePath)
    },
    async beforeImageUpload(rawFile) {
      const fileName = rawFile.name
      const baseFileName = fileName.substring(0, fileName.lastIndexOf('.'))
      // const { data } = await this.$api.getUploadUrl({ filename: fileName })
      // console.log(data, 'data');
      // this.action = data.result.url
      // this.fileKey = data.result.fileKey
      // this.iconUploadUrl = data.result.uploadUrl
      const imgSize = rawFile.size / 1024 / 1024 < 10
      const imgType = ['image/jpeg', 'image/png', 'image/gif']
      if (!imgType.includes(rawFile.type))
        message.notifyWarning('上传图片不符合所需的格式！')
      if (!imgSize) message.notifyWarning(`上传图片大小不能超过 10M！`)
      return imgType.includes(rawFile.type) && imgSize
    },
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        areaName: '',
      }
      this.handleSearch()
    },

    // 分页相关
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },

    // 新增
    handleAdd() {
      this.dialogType = 'add'
      this.form = {
        floorId: '',
        // areaId: '',
        categoryId: '',
        name: '',
        shopNumber: '',
        address: '',
        logo: '',
        imageUrl: [],
        // rating: 0,
        // ratingText: '',
        // reviewCount: 0,
        startTime: '09:30',
        endTime: '21:30',
        status: 1,
        description: '',
      }
      this.dialogVisible = true
    },

    // 编辑
    handleEdit(row) {
      this.dialogType = 'edit'
      console.log(row, 'row');
      this.form = { ...row, imageUrl: row.imageUrl || [] }
      this.dialogVisible = true
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确认删除吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await this.$api.deleteShop(row.id)
          this.$message.success('删除成功')
          this.getList()
        } catch (error) {
          console.error('删除失败：', error)
        }
      }).catch(() => { })
    },


    // 提交表单
    handleSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            if (this.dialogType === 'add') {
              await this.$api.addShopSp(this.form)
              this.$message.success('新增成功')
            } else {
              await this.$api.updateShopSp(this.form)
              this.$message.success('编辑成功')
            }
            this.dialogVisible = false
            this.getList()
          } catch (error) {
            console.error(this.dialogType === 'add' ? '新增失败：' : '编辑失败：', error)
          }
        }
      })
    },

    // 重置表单
    resetForm() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
      this.form = {
        name: '',
        title: '',
        imageUrl: '',
        address: '',
        phone: '',
        description: ''
      }
    }
  }
}
</script>

<style scoped lang="scss">
.dialog_height {
  height: 60vh;
  overflow: hidden;
  overflow-y: auto;
}

.image-item {
  position: relative;
}

.delete-image {
  position: absolute;
  bottom: 15px;
  right: 0px;
  width: 100%;
  height: 20px;
  font-size: 14px;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  cursor: pointer;
  z-index: 1000;
  line-height: 20px;
}

.flex_flex {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.flex_contents {
  height: 42px;
  display: flex;
  align-items: center;
}

.image-uploader {
  .uploaded-image {
    width: 140px;
    height: 140px;
    object-fit: cover;
    border-radius: 4px;
  }

  .upload-placeholder {
    width: 140px;
    height: 140px;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: border-color 0.3s;

    &:hover {
      border-color: #409EFF;
    }

    .el-icon-plus {
      font-size: 28px;
      color: #8c939d;
    }

    .upload-text {
      font-size: 12px;
      color: #8c939d;
      margin-top: 8px;
    }
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.text-center {
  text-align: center;
  line-height: 40px;
}

.merchant-list {
  padding: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>